import 'package:flutter/material.dart';
// import 'photos.dart';
import '../classificationList.dart';
import 'package:flutter/cupertino.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'list_message.dart';
import '../ads/app_open_ad_manager.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import '../ads/ads_unit_id.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CategoryMessagePage extends StatefulWidget {
  const CategoryMessagePage({
    super.key,
  });

  @override
  State<CategoryMessagePage> createState() => _MyCategoryMessagePageState();
}

class _MyCategoryMessagePageState extends State<CategoryMessagePage> {
  bool isMember = false;

  List categoryList = [
    {
      "id": 1,
      "category": "Buenos días",
      "slug": "good-morning",
    },
    {
      "id": 2,
      "category": "Feliz cumpleaños",
      "slug": "birthday",
    },
    {
      "id": 3,
      "category": "Amor",
      "slug": "love",
    },
    {
      "id": 4,
      "category": "Buenas tardes",
      "slug": "good-evening",
    },
    {
      "id": 5,
      "category": "Buenas noches",
      "slug": "good-night",
    }
  ];
  bool isLoading = false;
  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;

  final controller = ScrollController();

  static const _insets = 12.0;
  BannerAd? _inlineAdaptiveAd;
  bool _isLoaded = false;
  AdSize? _adSize;
  // late Orientation _currentOrientation;
  double get _adWidth => MediaQuery.of(context).size.width - (2 * _insets);


  // 调用公共方法
  // void fetchData() async {
  //   setState(() {
  //     isLoading = true;
  //   });
  //   try {
  //     String url = 'https://apken.oss-us-west-1.aliyuncs.com/goodmorning-es/json/category.json'; // 替换为你的 URL
  //     List<dynamic> jsonData = await ApiService.fetchJsonData(url);
  //     // print(jsonData);
  //     setState(() {
  //       isLoading = false;
  //     });
  //     setState(() {
  //       categoryList = jsonData[0]['list'];
  //     });

  //   } catch (e) {
  //     setState(() {
  //       isLoading = false;
  //     });
  //     print(e);
  //   }
  // }

  Future<void> _logScreenView() async {
    await analytics.logScreenView(
      screenName: 'Category Message Page ES',
      screenClass: 'CategoryMessagePage_ES',
    );
    // setMessage('setCurrentScreen succeeded');
  }

  Future<int> _getAdStatus() async {
    final prefs = await SharedPreferences.getInstance();
    int status = prefs.getInt('inlineAdStatus') ?? 1;
    return status;
  }

  void _loadInlineAd() async {
    int adStatus = await _getAdStatus();
    if (adStatus != 1) {
      return;
    }

    await _inlineAdaptiveAd?.dispose();
    setState(() {
      _inlineAdaptiveAd = null;
      _isLoaded = false;
    });

    // Get an inline adaptive size for the current orientation.
    AdSize size = AdSize.getCurrentOrientationInlineAdaptiveBannerAdSize(
        _adWidth.truncate());

    _inlineAdaptiveAd = BannerAd(
      // TODO: replace this test ad unit with your own ad unit.
      adUnitId: AdsUnitId.inlineAdaptive,
      size: size,
      request: AdRequest(),
      listener: BannerAdListener(
        onAdLoaded: (Ad ad) async {
          // print('Inline adaptive banner loaded: ${ad.responseInfo}');

          // After the ad is loaded, get the platform ad size and use it to
          // update the height of the container. This is necessary because the
          // height can change after the ad is loaded.
          BannerAd bannerAd = (ad as BannerAd);
          final AdSize? size = await bannerAd.getPlatformAdSize();
          if (size == null) {
            print('Error: getPlatformAdSize() returned null for $bannerAd');
            return;
          }

          setState(() {
            _inlineAdaptiveAd = bannerAd;
            _isLoaded = true;
            _adSize = size;
          });
        },
        onAdFailedToLoad: (Ad ad, LoadAdError error) {
          print('Inline adaptive banner failedToLoad: $error');
          ad.dispose();
        },
      ),
    );
    await _inlineAdaptiveAd!.load();
  }

  Widget _getAdWidget() {
    return OrientationBuilder(
      builder: (context, orientation) {
        if (
            _inlineAdaptiveAd != null &&
            _isLoaded &&
            _adSize != null) {
          return Align(
              child: Container(
                margin: const EdgeInsets.only(top: 12),
            width: _adWidth,
            height: _adSize!.height.toDouble(),
            child: AdWidget(
              ad: _inlineAdaptiveAd!,
            ),
          ));
        }
        // Reload the ad if the orientation changes.
        // if (_currentOrientation != orientation) {
        //   _currentOrientation = orientation;
        //   _loadAd();
        // }
        return Container();
      },
    );
  }

  @override
  void dispose() {
    _inlineAdaptiveAd?.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    _logScreenView();

    _loadInlineAd();

  }

  @override
  Widget build(BuildContext context) {
    
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('images/message_bg.png'), 
          fit: BoxFit.cover
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: PreferredSize(
          preferredSize: const Size.fromHeight(60),
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  offset: const Offset(0, 2),
                  blurRadius: 6.0,
                ),
              ],
            ),
            child: AppBar(
              backgroundColor: Colors.white,
              title: const Text(
                'Categoría',
                style:
                    TextStyle(fontFamily: 'OpenSans', color: Colors.black, fontWeight: FontWeight.bold),
              ),
              
            ),
          ),
        ),
        body: SingleChildScrollView(
          controller: controller,
          child:  Padding(
            padding: const EdgeInsets.only(left: 16, right: 16, bottom: 16),
            child: Column(
              children: [
                // for (var categoryItem in categoryList) 
                //   Article(classificationItem: categoryItem)
                for (var index = 0; index < categoryList.length; index++)
                  ...[
                    Article(
                      classificationItem: categoryList[index],
                    ),
                    // 在第二个分类后插入广告
                    if (index == 0) 
                      _getAdWidget(), // 替换为你的广告组件
                  ]
              ],
            ),
          ),
        ) 
      ),
    ) ;
    
  }
}

class Article extends StatelessWidget {
  final Map<String, dynamic> classificationItem;
  const Article({
    super.key,
    required this.classificationItem,
  });

  @override
  Widget build(BuildContext context) {
    // var slug = classificationItem.replaceAll(' ', '_');
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) =>
              ListMessagePage(slug: classificationItem['slug']),
          ),
        );
      },
      child: Container(
        height: 120,
        margin: const EdgeInsets.only(top: 16),
        padding: const EdgeInsets.only(left: 16, right: 16),
        decoration: const BoxDecoration(
          color: Color.fromRGBO(255, 255, 255, .85),
          borderRadius: BorderRadius.all(Radius.circular(8)),
          boxShadow: [
            BoxShadow(
              color: Colors.black12,
              offset: Offset(0, 2),
              blurRadius: 6.0,
            ),
          ],
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              width: 26,
              height: 26,
              child: Image.asset('images/category/${classificationItem['slug']}.webp'),
            ),
            const SizedBox(width: 10),
            Expanded(
                child: Text(
              classificationItem['category'],
              style: const TextStyle(
                fontSize: 18,
                fontFamily: 'OpenSans',
              ),
            )),
            const Icon(
              CupertinoIcons.arrow_right_circle,
              size: 30,
              color: Color.fromRGBO(0, 0, 0, .5),
            ),
          ],
        ),
      ),
    );
  }
}
